package com.bjsxt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.enums.ApiErrorCode;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.bjsxt.domain.SysMenu;
import com.bjsxt.feign.JwtToken;
import com.bjsxt.feign.OAuth2FeignClient;
import com.bjsxt.model.LoginResult;
import com.bjsxt.service.SysLoginService;
import com.bjsxt.service.SysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysLoginServiceImpl implements SysLoginService {

    @Autowired
    private OAuth2FeignClient oAuth2FeignClient;
    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${basic.token:Basic Y29pbi1hcGk6Y29pbi1zZWNyZXQ=}")
    private String basicToken;

    @Override
    public LoginResult login(String username, String password) {
        log.info("用户{}开始登录",username);

        //1.获取token 远程调用认证服务
           //ResponseEntity<JwtToken> tokenResponseEntity = oAuth2FeignClient.getToken("password",username,password,"admin_type",basicToken);
        ResponseEntity<JwtToken> tokenResponseEntity = oAuth2FeignClient.getToken("password", username, password, "admin_type", basicToken);

            if(tokenResponseEntity.getStatusCode()!= HttpStatus.OK){
                throw  new ApiException(ApiErrorCode.FAILED);
            }
            JwtToken jwtToken = tokenResponseEntity.getBody();
            log.info("远程调用授权服务器成功，获取token为{}", JSON.toJSONString(jwtToken,true));
            String token = jwtToken.getAccess_token();


        //2.查询菜单数据
        Jwt jwt = JwtHelper.decode(token);
        String claims = jwt.getClaims();
        JSONObject jwtJson = JSON.parseObject(claims);
        Long userid = Long.valueOf(jwtJson.getString("user_name") ) ;
        List<SysMenu> menus = sysMenuService.getMenusByUserId(userid);
        JSONArray authorities1 = jwtJson.getJSONArray("authorities");

        //3.查询权限数据
        List<SimpleGrantedAuthority> authorities  =  authorities1.stream()
                                                                .map(authority->new SimpleGrantedAuthority(authority.toString()))
                                                                .collect(Collectors.toList());
       //4.token存入redis
        redisTemplate.opsForValue().set(token,"",jwtToken.getExpires_in(), TimeUnit.SECONDS);
        return new LoginResult(jwtToken.getToken_type()+" "+token,menus,authorities);
    }
}
